using System.Collections.Generic;
using FishFillets.ObjectLogic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;

namespace FishFillets.GameComponents
{
    /// <summary>
    /// Class responsible for playing music in the game.
    /// </summary>
    public class MusicComponent : GameComponent
    {
        // A dictionary of loaded music tracks.
        public Dictionary<string, Song> Songs{ get; set; }

        public string CurrentSong { get; set; }

        private readonly ContentManager contentManager;

        public MusicComponent(Game game, ContentManager contentManager)
            : base(game)
        {
            this.contentManager = contentManager;
            Songs = new Dictionary<string, Song>();
            CurrentSong = string.Empty;
        }

        public override void Update(GameTime gameTime)
        {
            // If music playback is not allowed
            if (!MediaPlayer.GameHasControl) return;

            string song = GameController.Instance.MusicTrack;
            if (song == CurrentSong) return;

            CurrentSong = song;
            if (string.IsNullOrWhiteSpace(CurrentSong))
            {
                // stop music track
                MediaPlayer.Stop();
                return;
            }

            if (!Songs.ContainsKey(CurrentSong))
            {
                // Load our song
                Songs.Add(CurrentSong, contentManager.Load<Song>(CurrentSong));
            }

            // Play the song, repeating
            MediaPlayer.IsRepeating = true;
            MediaPlayer.Volume = Settings.MusicVolume;
            MediaPlayer.Play(Songs[CurrentSong]);
        }
    }
}
